import {
    createRouter,
    createWebHashHistory,
    createWebHistory,
} from "vue-router";

// 1. 定义路由组件.
// 也可以从其他文件导入
// const Home = { template: "<div>Home Page</div>" };
// const About = { template: "<div>About Page</div>" };
import Home from "../views/Home.vue";
import About from "../views/About.vue";
import User from "../views/User.vue";
import NotFound from "../views/NotFound.vue";
import UserGeneric from "../views/UserGeneric.vue";
import NestedUser from "../views/NestedUser.vue";
import NestedUser2 from "../views/NestedUser2.vue";
import ProNav from "../views/ProNav.vue";
import Goods from "../views/Goods.vue";
import Promotion from "../views/Promotion.vue";
import SearchUser from "../views/SearchUser.vue";
import Login from "../views/Login.vue";

import Sidebar from "../components/Sidebar.vue";

const Register = () => import("../views/Register.vue");

/* 路由守卫函数 */
function removeQueryParams(to) {
    if (Object.keys(to.query).length)
        return { path: to.path, query: {}, hash: to.hash };
}

function removeHash(to) {
    if (to.hash) return { path: to.path, query: to.query, hash: "" };
}

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
    { path: "/", component: Home, name: "homepage" },
    { path: "/home", redirect: "/" },
    { path: "/family", redirect: { name: "homepage" } },
    { path: "/about", component: About },
    { path: "/login", component: Login, name: "Login" },

    // 动态字段以冒号开始
    {
        path: "/users/:id",
        name: "user",
        component: User,
        props: true,
        meta: { transition: "slide-left" },
    },

    // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
    { path: "/:pm(.*)*", name: "NotFound", component: NotFound },

    // 将匹配以 `/user-` 开头的所有内容，并将其放在 `$route.params.afterUser` 下
    { path: "/user-:au(.*)", component: UserGeneric },

    // 嵌套路由
    {
        path: "/nuser/:id",
        component: NestedUser2,
        children: [
            {
                // 当 /user/:id/posts 匹配成功
                // UserPosts 将被渲染到 User 的 <router-view> 内部
                path: "profile",
                component: () => import("../components/UserProfile.vue"),
            },
            {
                // 当 /user/:id/posts 匹配成功
                // UserPosts 将被渲染到 User 的 <router-view> 内部
                path: "posts",
                component: () => import("../components/UserPosts.vue"),
            },
        ],
    },

    // 嵌套视图
    {
        path: "/nuser2/:id",
        alias: "/nu/:id",
        component: NestedUser2,
        children: [
            {
                path: "profile",
                components: {
                    default: () => import("../components/UserPosts.vue"),
                    helper: () => import("../components/UserProfile.vue"),
                },
                alias: ["/:id", ""],
            },
        ],
    },

    // 编程式导航
    { path: "/pronav", component: ProNav },
    { path: "/register", component: Register },

    // 重定向
    {
        // /search/screens -> /search?q=screens
        path: "/search/:searchText",
        redirect: (to) => {
            // 方法接收目标路由作为参数
            // return 重定向的字符串路径/路径对象
            return { path: "/search", query: { q: to.params.searchText } };
        },
    },

    // 有命名视图的路由
    {
        path: "/goods/:id",
        components: { default: Goods, sidebar: Sidebar },
        props: { default: true, sidebar: false },
    },

    // props为一个对象
    {
        path: "/promotion",
        component: Promotion,
        props: { newsletterPopup: false, age: 123 },
        // beforeEnter: (to, from) => {
        //     // reject the navigation
        //     console.log("promotion beforeEnter");
        //     return false;
        // },
        beforeEnter: [removeQueryParams, removeHash],
    },
    {
        path: "/search",
        component: SearchUser,
        props: (route) => ({ query: route.query.q }),
    },
];

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    // history: createWebHashHistory(),
    history: createWebHistory(),
    routes, // `routes: routes` 的缩写
});

// router.beforeEach((to, from) => {
//     console.log("router.beforeEach",from,to);
//     // 返回 false 以取消导航
//     return true;
// });

// GOOD
router.beforeEach((to, from, next) => {
    // console.log("router.beforeEach", from, to);

    // const random = Math.random();
    // if (to.name !== "Login" && random < 0.33) next({ name: "Login" });
    // else if (random < 0.67) {
    //     throw Error("这是一个错误");
    // } else {
    //     next();
    // }
    next();
});

router.afterEach((to, from, failure) => {
    // console.log("router.afterEach", from, to);
    // console.log("failure", failure);
});

export default router;
